Skip to content

Add array assertions about unsealed arrays#5722

Open
VincentLanglet wants to merge 3 commits into
phpstan:2.2.xfrom
VincentLanglet:sealedAssertions
Open

Add array assertions about unsealed arrays#5722
VincentLanglet wants to merge 3 commits into
phpstan:2.2.xfrom
VincentLanglet:sealedAssertions

Conversation

@VincentLanglet
Copy link
Copy Markdown
Contributor

I'd like you point of view of the behavior expected here

@phpstan-bot
Copy link
Copy Markdown
Collaborator

You've opened the pull request against the latest branch 2.2.x. PHPStan 2.2 is not going to be released for months. If your code is relevant on 2.1.x and you want it to be released sooner, please rebase your pull request and change its target to 2.1.x.

function sealedArrayFillKeys(array $sealed, array $unsealed): void
{
assertType("array{1: 'b', 2: 'b', 3: 'b'}", array_fill_keys($sealed, 'b'));
assertType("array{1: 'b', 2: 'b', 3: 'b', ...<0|1, 'b'>}", array_fill_keys($unsealed, 'b'));
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is correct.

But you might want to improve the array because ...<0|1, 'b'> is kinda complicated for nothing:

  • Since the 1 key already exists, we might want to simplify to
array{1: 'b', 2: 'b', 3: 'b', ...<0, 'b'>}

maybe ?

  • Then it could be just
array{1: 'b', 2: 'b', 3: 'b', 0?: 'b'}

function sealedArrayFlip(array $sealed, array $unsealed): void
{
assertType('array{1: 0, 2: 1, 3: 2}', array_flip($sealed));
assertType('array{1: int, 2: 1, 3: 2, 0?: int, ...<0|1, int>}', array_flip($unsealed));
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what's expected here, currently the type is

array{1: 0, 2: 1, 3: 2, ...<0|1, int>}

but this gives array_flip($unsealed)[1] to be considered as 0 instead of any integer.

This can be fixed in the ConstantArrayType::flipArray with an extra

$builder->setOffsetValueType($unsealedValue->toArrayKey(), $unsealedKey, true);

but in the same way I dunno if you like the result with the useless ...<0|1, int> since 0 and 1 are already declared in the array.

@VincentLanglet VincentLanglet marked this pull request as ready for review May 20, 2026 15:37
@phpstan-bot
Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants